package com.bjsxt.service.impl;

import com.bjsxt.geetest.GeetestLib;
import com.bjsxt.geetest.GeetestLibResult;
import com.bjsxt.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @ClassName: GeetestServiceImpl
 * @Author: chenyu
 * @Date: 2025/3/12 15:53
 */
@Service
public class GeetestServiceImpl implements GeetestService{

    @Autowired
    private GeetestLib geetestLib;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public static final String DIGEST_MOD = "md5";

    public static final String CLIENT_WEB = "web";

    @Override
    public GeetestLibResult register(String uuid) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("digestmod", DIGEST_MOD);
        paramMap.put("user_id", uuid);
        paramMap.put("client_type", CLIENT_WEB);
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        paramMap.put("ip_address", IpUtil.getIpAddr(requestAttributes.getRequest()));
        GeetestLibResult result = geetestLib.register(DIGEST_MOD, paramMap); //和极验服务器交互
        // 将结果状态写到session中，此处register接口存入session，后续validate接口会取出使用
        // 注意，此demo应用的session是单机模式，格外注意分布式环境下session的应用
//        request.getSession().setAttribute(GeetestLib.GEETEST_SERVER_STATUS_SESSION_KEY, result.getStatus());
        redisTemplate.opsForValue().set(GeetestLib.GEETEST_SERVER_STATUS_SESSION_KEY + ":" + uuid,
                result.getStatus(), 180, TimeUnit.SECONDS);
//        request.getSession().setAttribute("userId", userId);
        redisTemplate.opsForValue().set(GeetestLib.GEETEST_SERVER_USER_KEY + ":" + uuid, uuid, 180, TimeUnit.SECONDS);
        // 注意，不要更改返回的结构和值类型
        return result;
    }
}
